﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class admin_project_ActiveUser : System.Web.UI.Page
{
    static User userToEdit;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // list all projects
            var query = from item in ApplicationGlobalVariables.KillDaBugsDatabase.Projects
                        select new
                        {
                            item.Name,
                            item.ProjectId
                        };

            foreach (var project in query)
            {
                ddlProjectName.Items.Add(new ListItem(project.Name, project.ProjectId.ToString()));
            }

            // hide info panel by default
            ltrInfo.Text = "hide";
        }
        else
        {
            // reset result message
            ltrResultMessage.Text = "";
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        userToEdit = UserManagement.GetUser(txtUserName.Text.Trim());
        if (userToEdit != null)
        {
            txtFullName.Text = userToEdit.Fullname;
            txtEmail.Text = userToEdit.Email;
            txtOrganization.Text = userToEdit.CustomInfo;

            // show info panel
            ltrInfo.Text = "";
        }
        else
        {
            ltrResultMessage.Text = "Cannot find user with username \"" + txtUserName.Text + "\". Please try again!";
            // hide info panel
            ltrInfo.Text = "hide";
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        // check if user is already assigned to this project
        var query = from item in ApplicationGlobalVariables.KillDaBugsDatabase.User_Projects
                    where item.Username == userToEdit.Username && item.ProjectId == int.Parse(ddlProjectName.SelectedValue)
                    select 0;
        if (!query.Any())
        {
            ltrResultMessage.Text = "User is already unassigned to this project";
            return;
        }

        ProjectManagement projectMannagement = new ProjectManagement(Master.Master.CurrentUserManagement.CurrentUser);

        bool updateOK = projectMannagement.UnassignUserFromProject(userToEdit.Username, int.Parse(ddlProjectName.SelectedValue));

        if (updateOK)
        {
            ltrResultMessage.Text = "User Removed from Project Successfully!";
        }
        else
            ltrResultMessage.Text = "User Unassignment Failed due to Database Error!";
    }
}